package com.gzk.hrm.userDetails;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gzk.hrm.domain.Login;
import com.gzk.hrm.domain.Permission;
import com.gzk.hrm.mapper.PermissionMapper;
import com.gzk.hrm.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据数据库查询

        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);

        Login user = loginService.selectOne(wrapper);

        List<SimpleGrantedAuthority> authorities = null;

        //根据userid查权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(user.getId());

        //遍历设置权限
        authorities = permissions.stream().map(permission ->
                new SimpleGrantedAuthority(permission.getSn())
        ).collect(Collectors.toList());

        //打印权限
        authorities.forEach(authority-> System.out.println(authority.getAuthority()));

        return new org.springframework.security.core.userdetails.User(
                JSON.toJSONString(user),
                user.getPassword(),
                user.getEnabled(),
                user.getAccountNonExpired(),
                user.getCredentialsNonExpired(),
                user.getAccountNonLocked(),
                authorities
        );
    }
}
